package cg.studio.algorithm.permutation;

import java.util.SortedMap;
import java.util.TreeMap;

public class PermutationUtils
{
  /**
   * use map instead of array as we don't limit string to ascii, number or others
   * @param str
   * @return
   */
  /********************/
  public static SortedMap< Character, Integer > getCharToCountMap( String str )
  {
    if( str == null || str.isEmpty() )
      return null;
    str = str.toUpperCase();
    
    SortedMap< Character, Integer > charToCountMap = new TreeMap< Character, Integer >();
    
    str = str.toUpperCase();
    char[] chars = str.toCharArray();
    for( char theChar : chars )
    {
      Integer count = charToCountMap.get( theChar );
      if( count == null )
      {
        charToCountMap.put( theChar, 1 );
      }
      else
      {
        //Integer is immutable, we can't change its value
        charToCountMap.put( theChar, count+1 );
      }
    }
    return charToCountMap;
  }
  
  /**
   * decrease the count of <theChar> of map <charToCountMap>
   * remove the entry from the map if the count reach to zero
   * @param charToCountMap
   * @param theChar
   * @return
   */
  public static SortedMap< Character, Integer > decreaseCharCount( SortedMap< Character, Integer > charToCountMap, char theChar )
  {
    Integer count = charToCountMap.get( theChar );
    if( count == null || count < 1 )
      throw new IllegalStateException( "Try to decrease the count which does not exist or zero." );
    if( count == 1 )
      charToCountMap.remove( theChar );   //remove the entry
    else
      charToCountMap.put( theChar, --count );
    return charToCountMap;
  }

  /**
   * increase the count of <theChar> of map <charToCountMap>
   * insert the entry if previous doesn't exist
   * 
   * @param charToCountMap
   * @param theChar
   * @return
   */
  public static SortedMap< Character, Integer > increaseCharCount( SortedMap< Character, Integer > charToCountMap, char theChar )
  {
    Integer count = charToCountMap.get( theChar );
    if( count == null )
      count = 0;
    charToCountMap.put( theChar, ++count );
    return charToCountMap;
  }

}
